#pragma once
#include<iostream>
using namespace std;

// 枚举值表示颜色
enum  Color
{
	RED,
	BLACK
};

// 默认按key/value结构实现
template<class K, class V>
struct RBTreeNode
{
	// 这里更新控制平衡也要加入parent指针
	pair<K, V> _kv;
	RBTreeNode<K, V>* _left;
	RBTreeNode<K, V>* _right;
	RBTreeNode<K, V>* _parent;
	Color _col;

	RBTreeNode(const pair<K, V>& kv)
		:_kv(kv),
		_left(nullptr),
		_right(nullptr),
		_parent(nullptr),
		_col(RED)
	{
	}
};

template<class K, class V>
class RBTree
{
	typedef RBTreeNode<K, V> Node;
public:
	RBTree() = default;
	~RBTree()
	{
		Destory(_root);
	}
	// 旋转代码的实现跟AVL树是一样的，只是不需要更新平衡因子
	bool Insert(const pair<K, V>& kv)
	{
		if (_root == nullptr) {
			_root = new Node(kv);
			_root->_col = BLACK;
			return true;
		}
		Node* cur = _root;
		Node* parent = nullptr;
		while (cur)
		{
			if (kv.first > cur->_kv.first) {
				parent = cur;
				cur = cur->_right;
			}
			else if (kv.first < cur->_kv.first) {
				parent = cur;
				cur = cur->_left;
			}
			else {
				return false;
			}
		}
		cur = new Node(kv);
		// 新增节点，颜色红色
		cur->_col = RED;
		cur->_parent = parent;
		if (kv.first > parent->_kv.first) {
			parent->_right = cur;
		}
		else {
			parent->_left = cur;
		}
		//对不满足规则的情况进行调整
		while (parent && parent->_col == RED)
		{
			Node* grandfather = parent->_parent;
			//   g
			// p   u
			if (grandfather->_left == parent) {
				Node* uncle = grandfather->_right;
				if (uncle && uncle->_col == RED) {
					// 叔叔存在且为红，变色再继续往上处理
					parent->_col = BLACK;
					uncle->_col = BLACK;
					grandfather->_col = RED;
					cur = grandfather;
					parent = cur->_parent;
				}
				else {
					// 叔叔不存在或存在且为黑，旋转+变色
					if (parent->_left == cur) {
						//    g
						//  p   u
						//c
						//单旋
						RotateR(grandfather);
						grandfather->_col = RED;
						parent->_col = BLACK;
					}
					else {
						//    g
						//  p   u
						//    c
						//双旋
						RotateL(parent);
						RotateR(grandfather);
						grandfather->_col = RED;
						cur->_col = BLACK;
					}
					break;
				}
			}
			else {
				Node* uncle = grandfather->_left;
				if (uncle && uncle->_col == RED) {
					// 叔叔存在且为红，变色再继续往上处理
					parent->_col = BLACK;
					uncle->_col = BLACK;
					grandfather->_col = RED;
					cur = grandfather;
					parent = cur->_parent;
				}
				else {
					// 叔叔不存在或存在且为黑，旋转+变色
					if (parent->_right == cur) {
						//   g
						// u   p
						//       c
						// 单旋
						RotateL(grandfather);
						grandfather->_col = RED;
						parent->_col = BLACK;
					}
					else {
						//   g
						// u   p
						//   c
						// 双旋
						RotateR(parent);
						RotateL(grandfather);
						grandfather->_col = RED;
						cur->_col = BLACK;
					}
					break;
				}
			}
		}
		_root->_col = BLACK;
		return true;
	}
	// 删除
	bool Erase(const K& key)
	{
		// 树为空则无须删除
		if (_root == nullptr) return false;
		Node* cur = Find(key);
		if (cur == nullptr) {
			// 找不到指定节点则返回false
			return false;
		}
		Node* parent = cur->_parent;
		if (cur->_left && cur->_right)
		{
			// 如果被删除的节点既有左孩子又有右孩子，则去找右子树的最小节点替代被删除的节点
			Node* minRight = cur->_right;
			Node* minRightParent = cur;
			while (minRight->_left)
			{
				minRightParent = minRight;
				minRight = minRight->_left;
			}
			//替换
			cur->_kv = minRight->_kv;
			cur = minRight;
			parent = minRightParent;
		}
		// 被删除节点只有0/1个孩子
		Node* child = nullptr;
		if (cur->_left) child = cur->_left;
		else child = cur->_right;

		if (child) child->_parent = parent;
		if (parent == nullptr) {
			// 被删除节点是根节点，则孩子节点变为根节点
			_root = child;
			if (_root) _root->_col = BLACK; // 细节，如果孩子节点也为空则红黑树为空，无须设置颜色
			delete cur;
			return true;
		}
		if (child) {
			// 如果删除节点只有一个孩子，则parent和child建立联系，并且将child设置为黑色节点
			if (parent->_left == cur) {
				parent->_left = child;
			}
			else {
				parent->_right = child;
			}
			child->_col = BLACK;
		}
		else {
			// 删除节点没有孩子的情况
			Node* pNode = cur;
			if (pNode->_col == RED) {
				// 删除节点是红色节点，则直接删除无须任何调整
				if (parent->_left == cur) {
					parent->_left = nullptr;
				}
				else {
					parent->_right = nullptr;
				}
				delete cur;
				return true;
			}
			// pNode表示双黑节点
			while (pNode)
			{
				if (pNode->_col == RED || pNode == _root)
				{
					// 如果遇到红节点或者根节点则双黑节点变为单黑节点
					pNode->_col = BLACK;
					break;
				}
				Node* bro = nullptr;
				if (parent->_left == pNode)
				{
					// 兄弟节点是父节点的右孩子
					bro = parent->_right;
					if (bro->_col == BLACK)
					{
						// 兄弟节点是黑节点
						Node* broR = bro->_right;
						Node* broL = bro->_left;
						if (broR && broR->_col == RED)
						{
							// RR型，颜色变化：broR变bro，bro变parent
							// 对parent进行左单旋，双黑节点变为单黑节点
							broR->_col = bro->_col;
							bro->_col = parent->_col;
							parent->_col = BLACK;
							RotateL(parent);
							break;
						}
						else if (broL && broL->_col == RED)
						{
							// RL型，颜色变化：broL变为parent，parent变黑
							// 对bro进行右单旋，对parent进行左单旋，双黑节点变为单黑节点
							broL->_col = parent->_col;
							parent->_col = BLACK;
							RotateR(bro);
							RotateL(parent);
							break;
						}
						else
						{
							// 兄弟都是黑色节点
							// 兄弟变为红色节点，双黑节点上移，遇红或根变单黑
							bro->_col = RED;
							pNode = parent;
							parent = parent->_parent;
						}
					}
					else
					{
						// 兄弟节点是红色
						// 兄弟节点变黑色，父亲节点变为红色
						// 以parent为旋转点朝双黑节点旋转（左单旋）
						// 保持双黑节点继续调整
						bro->_col = BLACK;
						parent->_col = RED;
						RotateL(parent);
					}
				}
				else
				{
					// 兄弟节点是父节点的左孩子
					bro = parent->_left;
					if (bro->_col == BLACK)
					{
						// 兄弟节点是黑节点
						Node* broR = bro->_right;
						Node* broL = bro->_left;
						if (broL && broL->_col == RED)
						{
							// LL型，颜色变化：broL变bro，bro变parent
							// 对parent进行右单旋，双黑节点变为单黑节点
							broL->_col = bro->_col;
							bro->_col = parent->_col;
							parent->_col = BLACK;
							RotateR(parent);
							break;
						}
						else if (broR && broR->_col == RED)
						{
							// LR型，颜色变化：broR变为parent，parent变黑
							// 对bro进行左单旋，对parent进行右单旋，双黑节点变为单黑节点
							broR->_col = parent->_col;
							parent->_col = BLACK;
							RotateL(bro);
							RotateR(parent);
							break;
						}
						else
						{
							// 兄弟都是黑色节点
							// 兄弟变为红色节点，双黑节点上移，遇红或根变单黑
							bro->_col = RED;
							pNode = parent;
							parent = parent->_parent;
						}
					}
					else
					{
						// 兄弟节点是红色
						// 兄弟节点变黑色，父亲节点变为红色
						// 以parent为旋转点朝双黑节点旋转（右单旋）
						// 保持双黑节点继续调整
						bro->_col = BLACK;
						parent->_col = RED;
						RotateR(parent);
					}
				}
			}
			// 断开删除节点cur和它的父节点的联系
			parent = cur->_parent;
			if (parent->_left == cur) {
				parent->_left = nullptr;
			}
			else {
				parent->_right = nullptr;
			}
			// 删除节点
			delete cur;
		}
		// 将根节点设置为黑色节点
		_root->_col = BLACK;
		return true;
	}
	// 查找
	Node* Find(const K& key)
	{
		Node* cur = _root;
		while (cur)
		{
			if (key > cur->_kv.first) {
				cur = cur->_right;
			}
			else if (key < cur->_kv.first) {
				cur = cur->_left;
			}
			else {
				return cur;
			}
		}
		return nullptr;
	}
	// 验证是否平衡
	bool IsBalance()
	{
		if (_root == nullptr) {
			return true;
		}
		if (_root->_col == RED) {
			return false;
		}
		// 参考值
		int refNum = 0;
		Node* cur = _root;
		while (cur)
		{
			if (cur->_col == BLACK) {
				refNum++;
			}
			cur = cur->_left;
		}
		return Check(_root, 0, refNum);
	}
	void InOrder()
	{
		_InOrder(_root);
	}
	int Height()
	{
		return _Height(_root);
	}
	int Size()
	{
		return _Size(_root);
	}
protected:
	// 右单旋
	void RotateR(Node* parent)
	{
		Node* subL = parent->_left;
		Node* subLR = subL->_right;

		subL->_right = parent;
		parent->_left = subLR;
		if (subLR)
			subLR->_parent = parent;
		Node* parentParent = parent->_parent;
		parent->_parent = subL;
		if (parentParent == nullptr) {
			// 如果parent为根节点则更新根节点
			_root = subL;
			subL->_parent = nullptr;
		}
		else {
			// subL和parentParent建立联系
			if (parentParent->_left == parent) {
				parentParent->_left = subL;
			}
			else {
				parentParent->_right = subL;
			}
			subL->_parent = parentParent;
		}
	}

	//左单旋
	void RotateL(Node* parent)
	{
		Node* subR = parent->_right;
		Node* subRL = subR->_left;

		subR->_left = parent;
		parent->_right = subRL;
		if (subRL)
			subRL->_parent = parent;
		Node* parentParent = parent->_parent;
		parent->_parent = subR;
		if (parentParent == nullptr) {
			// 如果parent为根节点则更新根节点
			_root = subR;
			subR->_parent = nullptr;
		}
		else {
			// subR和parentParent建立联系
			if (parentParent->_left == parent) {
				parentParent->_left = subR;
			}
			else {
				parentParent->_right = subR;
			}
			subR->_parent = parentParent;
		}
	}

	//检查
	bool Check(Node* root, int blackNum, const int& refNum)
	{
		if (root == nullptr) {
			if (blackNum != refNum) {
				cout << "存在黑色结点的数量不相等的路径" << endl;
				return false;
			}
			return true;
		}
		// 检查孩子不太方便，因为孩子有两个，且不一定存在，反过来检查父亲就方便多了
		if (root->_col == RED && root->_parent->_col == RED)
		{
			cout << root->_kv.first << "存在连续的红色节点" << endl;
			return false;
		}
		if (root->_col == BLACK)
		{
			blackNum++;
		}
		return Check(root->_left, blackNum, refNum) && Check(root->_right, blackNum, refNum);
	}

	int _Size(Node* root)
	{
		if (root == nullptr) return 0;
		return _Size(root->_left) + _Size(root->_right) + 1;
	}

	int _Height(Node* root)
	{
		if (root == nullptr)
			return 0;
		int leftHeight = _Height(root->_left);
		int rigthHeight = _Height(root->_right);
		return max(leftHeight, rigthHeight) + 1;
	}

	void _InOrder(Node* root)
	{
		if (root == nullptr) return;
		_InOrder(root->_left);
		cout << root->_kv.first << ":" << root->_kv.second << endl;
		_InOrder(root->_right);
	}

	void Destory(Node* root)
	{
		if (root == nullptr) return;
		if (root->_left) Destory(root->_left);
		if (root->_right) Destory(root->_right);
		delete root;
		root = nullptr;
	}
private:
	Node* _root = nullptr;
};